package com.htx.zqs.blesmartmask.ui.fragment;

import android.Manifest;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.htx.zqs.blesmartmask.MyApplication;
import com.htx.zqs.blesmartmask.R;
import com.htx.zqs.blesmartmask.adapter.RvDeviceAdapter;
import com.htx.zqs.blesmartmask.bean.Contants;
import com.htx.zqs.blesmartmask.bean.LimitInfo;
import com.htx.zqs.blesmartmask.bean.Numb;
import com.htx.zqs.blesmartmask.eventbus.MessageEvent;
import com.htx.zqs.blesmartmask.listeners.BmobListener;
import com.htx.zqs.blesmartmask.listeners.OkListener;
import com.htx.zqs.blesmartmask.ui.activity.MainActivity;
import com.htx.zqs.blesmartmask.ui.activity.StartCourseActivity;
import com.htx.zqs.blesmartmask.ui.activity.TestWaterActivity;
import com.htx.zqs.blesmartmask.ui.callback.MeBluetoothGattCallback;
import com.htx.zqs.blesmartmask.utils.BlEUtile;
import com.htx.zqs.blesmartmask.utils.BmobUtil;
import com.htx.zqs.blesmartmask.utils.LocationUtil;
import com.htx.zqs.blesmartmask.utils.OkhttpUtils;
import com.htx.zqs.blesmartmask.utils.SPUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.bmob.v3.exception.BmobException;

/**
 * Created by zhao on 2018/5/11.
 */

public class DeviceFragment extends BaseFragment {
    private static final int REQUEST_ACCESS_COARSE_LOCATION = 911;
    private static final int REQUEST_ENABLE_BT = 333;
    @InjectView(R.id.home_center_left_img)
    ImageView homeCenterLeftImg;

    @InjectView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @InjectView(R.id.home_center_right_img)
    ImageView homeCenterRightImg;
    @InjectView(R.id.home_buttom_img)
    ImageView homeButtomImg;
    @InjectView(R.id.testButton)
    Button testButton;
    @InjectView(R.id.startButton)
    Button startButton;
    @InjectView(R.id.rv_device)
    RecyclerView rvDevice;
    @InjectView(R.id.home_top_img1)
    ImageView mHomeTopImg1;
    private BluetoothAdapter bluetoothAdapter;
    private RvDeviceAdapter rvDeviceAdapter;
    private ArrayList devices = new ArrayList();
    private BluetoothLeScanner scanner;
    private BmobUtil bmobUtil;


    private String deviceId;
    private String mLastCourseName;
    private int mLimitCourseCount;
    private AlertDialog.Builder builder;
    private LocalBroadcastManager broadcastManager;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_device, container, false);
        ButterKnife.inject(this, view);
        // getBLEDataFromBmob("00:11:67:66:66:79");
        initView();
        initBluetooth();
        initData();
        initBroadcastRevicer();
        return view;
    }

    private void initBroadcastRevicer() {

//注册广播
        registerReceiver();
    }

    public void sendBroadcastTevice() {
        Intent intent = new Intent("scan");
        LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
    }

    /**
     * 注册广播接收器
     */
    private void registerReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(getActivity());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("scan");
        broadcastManager.registerReceiver(mAdDownLoadReceiver, intentFilter);
    }

    private BroadcastReceiver mAdDownLoadReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            scanDevice(true);
        }
    };

    private void initData() {
        deviceId = LocationUtil.getUniquePsuedoID();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!MyApplication.isConnected ){
//               || MyApplication.limitCount >= Contants.LIMIT_COUNT || MyApplication.limitSeconds >= (Contants.LIMIT_TIME * 60)) {
            scanDevice(true);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        //initBluetooth();
    }

    private void initBluetooth() {
        bluetoothAdapter = BlEUtile.getBleAdapter();

        if (Build.VERSION.SDK_INT >= 23) {
            if (checkLocatoinPermission()) {
                scanDevice(true);
                Log.e("nihao", "run: " + 444);
            } else {
                show();
            }
        } else {
            scanDevice(true);
            Log.e("nihao", "run: 5.0以下");
        }
    }

    private void show() {

        builder.setTitle(R.string.permission_error_title)
                .setMessage(R.string.permission_error_message_location)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_ACCESS_COARSE_LOCATION);
                    }
                })
                .show();
        if (swipeRefreshLayout != null) {
            //  swipeRefreshLayout.setRefreshing(true);
        }
    }

    private void initView() {
        builder = new AlertDialog.Builder(getContext());
        builder.setCancelable(false);
        rvDeviceAdapter = new RvDeviceAdapter(getActivity());
        rvDevice.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        rvDevice.setAdapter(rvDeviceAdapter);

        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    if (!MyApplication.isConnected) {
                        if (checkLocatoinPermission()) {
//                            if (!isScaning) {
//                                scanDevice(true);
//                            } else {
//                                isScaning = false;
//                                scanDevice(false);
//                            }
                            scanDevice(true);
                        } else {
                            show();
                        }
                        Log.e("nihao", "run: " + 111);
                    } else {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }
            });
            //   swipeRefreshLayout.setRefreshing(true);
            Log.e("nihao", "run: " + 222);
        }
    }

    @Override
    public void onPause() {
        isScaning = false;
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        broadcastManager.unregisterReceiver(mAdDownLoadReceiver);
        ButterKnife.reset(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        int code = event.getCode();
        if (code == 555) {
            // 更新界面
            devices.clear();
            rvDeviceAdapter.notifyDataSetChanged();
        }
    }

    @OnClick({R.id.testButton, R.id.startButton})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.testButton:

                if (MyApplication.isConnected) {
                    Intent intent = new Intent(getContext(), TestWaterActivity.class);
                    intent.putExtra("isTestWater", MyApplication.isTestWater);
                    startActivityForResult(intent, 10);
                } else {
                    goToBluetooth();
                }
                break;
            case R.id.startButton:
                // mLastCourseName = sp.getString(deviceId, null);
                try {
                    String name = (String) SPUtil.get(getActivity(), deviceId, "", "mLastCourseName");
                    if (name.equals("")) {
                        mLastCourseName = "";
                    } else {
                        mLastCourseName = MyApplication.getCourseFromIndex(Integer.parseInt(name));
                    }
                } catch (Exception e) {
                    mLastCourseName = (String) SPUtil.get(getActivity(), deviceId, "", "mLastCourseName");
                }
                mLimitCourseCount = (int) SPUtil.get(getContext(), deviceId, 0, "LimitCourseCount");

                Log.e("count", "onViewClicked: mLimitCourseCount 你到底是多少 " + mLimitCourseCount);
                Log.e("count", "onViewClicked: mLimitCourseCount 你到底是多少 " + mLastCourseName);
                if (MyApplication.isConnected) {
                    if (!MyApplication.isCourseExist) {
                        new AlertDialog.Builder(getContext()).setTitle(R.string.course_data_no_exit_title)
                                .setMessage(R.string.course_data_no_exit_message)
                                .setPositiveButton(R.string.ok, null)
                                .show();
                    } else {
                        if (mLastCourseName == "") {
                            startCourse();
                        } else {
                            if (MyApplication.selectCourse.
                                    getName().equals(mLastCourseName)) {
                                // Log.e("count", "onViewClicked: mLimitCourseCount 选中的走了吗 " +mLastCourseName+ mLimitCourseCount);
                                startCourse();

                            } else if (mLimitCourseCount >= Contants.LIMIT_COURSE_COUNT || mLimitCourseCount == 0) {
                                startCourse();
                            } else {
                                new AlertDialog.Builder(getContext()).setTitle(R.string.course_count_no_six_title)
                                        .setMessage(getResources().getString(R.string.cycle_message1) + mLastCourseName +
                                                getResources().getString(R.string.cycle_message2) + mLimitCourseCount + getResources().getString(R.string.cycle_message3))
                                        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                changeHomeFragmentUi();
                                            }
                                        })
                                        .show();
                            }
                        }
                    }
                } else {
                    ((MainActivity) getActivity()).goToBluetooth();
                }
                break;
        }
    }

    private void startCourse() {
        if (MyApplication.bluetoothState == Contants.STATE_NO_RUN) {
            if (MyApplication.isTestWater) {
                startActivityForResult(new Intent(getContext(), StartCourseActivity.class), 11);
//                builder.setTitle("请按照使用规范")
//                        .setMessage("开始新课程之前，请先保存您的皮肤状态")
//                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                            }
//                        })
//                        .show();
            } else {
                builder.setTitle(R.string.start_dialog_title)
                        .setMessage(R.string.start_dialog_message)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent1 = new Intent(getContext(), TestWaterActivity.class);
                                startActivityForResult(intent1, 10);
                            }
                        })
                        .show();
            }
        } else if (MyApplication.selectCourse.equals(MyApplication.runningCourse)) {
            startActivityForResult(new Intent(getContext(), StartCourseActivity.class), 11);

        } else {
            builder.setTitle(R.string.other_course_run_title)
                    .setMessage(R.string.other_course_run_message)
                    .setNegativeButton(R.string.other_course_run_negative_btn, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            MyApplication.isTestWater = true;
                            startActivityForResult(new Intent(getContext(), StartCourseActivity.class), 11);
                        }
                    })
                    .setPositiveButton(R.string.other_course_run_positive_btn, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Log.e("ceshi", "startCourse: " + MyApplication.selectCourse);
                            startNewCourse();

                        }
                    })
                    .show();
        }
    }

    private void changeHomeFragmentUi() {
        ((MainActivity) getActivity()).goToFragment(0);
        Intent intent = new Intent("jerry");
        intent.putExtra("change", "yes");
        intent.putExtra("mLastCourseName", mLastCourseName);
        LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
    }

    private void startNewCourse() {
        //先停止 正在运行的课程
        if (MyApplication.isTestWater) {
            MyApplication.meBluetoothGattCallback.stopCourse();
            startActivityForResult(new Intent(getContext(), StartCourseActivity.class), 11);

        } else {
            builder.setTitle(R.string.start_dialog_title)
                    .setMessage(R.string.start_dialog_message)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent1 = new Intent(getContext(), TestWaterActivity.class);
                            getActivity().startActivityForResult(intent1, 10);
                        }
                    })
                    .show();
        }
    }

    public void goToBluetooth() {
        builder.setTitle(R.string.blebroadcast_title).setMessage(R.string.blebroadcast_message)
                .setNegativeButton(R.string.cancle, null)
                .setPositiveButton(R.string.main_bluetooth_go, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        sendBroadcastTevice();
                    }
                })
                .show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10) {
            mLimitCourseCount = (int) SPUtil.get(MyApplication.appContext, deviceId, 0, "LimitCourseCount");
            if (mLimitCourseCount % 6 == 0 && MyApplication.isConnected && MyApplication.state == 0) {
                ((MainActivity) getActivity()).goToFragment(0);
                Toast.makeText(MyApplication.appContext, getResources().getString(R.string.start_course_choose), Toast.LENGTH_SHORT).show();
            }
            Log.e("=========device====" + requestCode, "=======432=");
            //  MyApplication.isTestWater = true;
        } else if (requestCode == 11) {
            //MyApplication.isTestWater = false;
        } else if (requestCode == Contants.CAMERA_REQUEST_CODE) {
            // startActivityForResult(new Intent(getContext(), StartCourseActivity.class), 11);
            if (requestCode == -1) {
                //照相成功   -1
            } else {
                //照相失败
            }
        } else if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == getActivity().RESULT_OK) {
                if (bluetoothAdapter.isEnabled()) {
                    Toast.makeText(getContext(), getResources().getString(R.string.main_bluetooth_on), Toast.LENGTH_SHORT).show();
                    //   this.scanDevice(true);
                } else {
                }
            } else {
                Toast.makeText(getContext(), getResources().getString(R.string.main_bluetooth_unon), Toast.LENGTH_SHORT).show();
            }
        }
    }

    // onResume 中进行调用
    private boolean checkLocatoinPermission() {
        Log.e("nihao", "run: " + 333);
        if (Build.VERSION.SDK_INT >= 23) {
            //判断是否有权限
            if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_ACCESS_COARSE_LOCATION) {
            if (permissions[0].equals(Manifest.permission.ACCESS_COARSE_LOCATION)
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户同意使用该权限
                scanDevice(true);
            } else {
                builder.setTitle(R.string.permission_error_title)
                        .setMessage(R.string.permission_error_message_location)
                        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_ACCESS_COARSE_LOCATION);
                            }
                        })
                        .show();
                swipeRefreshLayout.setRefreshing(false);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private Handler handler = new Handler();
    private boolean isScaning = false;

    public void scanDevice(boolean enable) {
        devices.clear();
        if (MyApplication.bluetoothGatt != null && MyApplication.bluetoothGatt.getDevice() != null) {
            devices.add(MyApplication.bluetoothGatt.getDevice());
        }
//        if (Build.VERSION.SDK_INT < 21) {
//            if (enable) {
//                handler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        isScaning = false;
//                        bluetoothAdapter.stopLeScan(mLeScanCallback);
//                        swipeRefreshLayout.setRefreshing(false);
//                    }
//                }, 2000);
//                isScaning = true;
//                bluetoothAdapter.startLeScan(mLeScanCallback);
//            } else {
//                isScaning = false;
//                bluetoothAdapter.stopLeScan(mLeScanCallback);
//                if (swipeRefreshLayout != null) {
//                    swipeRefreshLayout.setRefreshing(false);
//                }
//            }
//        } else {


        scanner = bluetoothAdapter.getBluetoothLeScanner();
        if (scanner != null) {
            Log.e("5.0", "showDevice: " + 555);
            scanner.startScan(scanCallBack);
            Log.e("5.0", "showDevice: " + 666);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    scanner.stopScan(scanCallBack);
                    Log.e("5.0", "showDevice: " + 777);
                    if (swipeRefreshLayout != null) {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }
            }, 3000);

        } else {
            if (bluetoothAdapter != null) {
                if (!bluetoothAdapter.isEnabled()) {
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                    swipeRefreshLayout.setRefreshing(false);
                }
            }
        }
    }

    private ScanCallback scanCallBack = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            swipeRefreshLayout.setRefreshing(false);
            Log.e("5.0", "showDevice: " + 000);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                BluetoothDevice device = result.getDevice();
                showDevice(device);
                Log.e("6.0", "showDevice3333333333: " + device);
                rvDeviceAdapter.notifyDataSetChanged();

            }
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            Log.e("5.0", "showDevice: " + "aaaa");
        }

        @Override
        public void onScanFailed(int errorCode) {
            Log.e("5.0", "showDevice: " + "bbbb");
//            new AlertDialog.Builder(getActivity()).setTitle(R.string.attention_please)
//                    .setMessage("取消")
//                    .setPositiveButton("请确认蓝牙面膜已开启，重新扫描", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            scanDevice(true);
//                        }
//                    })
//                    .show();
            swipeRefreshLayout.setRefreshing(false);
            //   scanDevice(true);
        }
    };

    HashMap map = new HashMap();

    private void showDevice(final BluetoothDevice device) {
        Log.e("5.0", "showDevice: " + 222);
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(false);
        }
        Log.e("5.0", "showDevice: " + 333);
        if (device.getAddress().indexOf("00:11:67") == 0 || device.getAddress().indexOf("10:A2:4E") == 0) {
            if ( !devices.contains(device) && device.getName().startsWith("Metis Genie Mask")) {
                devices.add(device);
                Log.e("nihao", "run: " + device);
                rvDeviceAdapter.setData(devices);
                rvDeviceAdapter.setOnItemClickListener(new RvDeviceAdapter.OnItemClickListener() {
                    @Override
                    public void onClick(final int position) {
                        if (!MyApplication.isConnected) {
                            try {
                                if (!getActivity().isFinishing()) {
                                    BlEUtile.getmKProgressHUD(getActivity()).setLabel(getResources().getString(R.string.connecting)).show();
                                }
                            } catch (Exception e) {
                                Log.e("e", "onSuccess: " + e.toString());
                            }
                            if (true) {
                                OkhttpUtils okhttpUtils = new OkhttpUtils(getActivity(), Contants.BLUE_TIME, new OkListener() {
                                    @Override
                                    public void onSuccess(int requestCode, String string) {
                                        Log.e("===603==", string + "====device===");
                                        Gson gson = new Gson();
                                        LimitInfo limitInfo = gson.fromJson(string, LimitInfo.class);
                                        LimitInfo.DataBean data = limitInfo.getData();
                                        MyApplication.limitSeconds = data.getMin();
                                        MyApplication.limitCount = data.getNumberlong();
                                        firstConnect(position);
                                    }

                                    @Override
                                    public void onError(int requestCode, IOException e) {
                                       // Toast.makeText(getContext(), getResources().getString(R.string.error_message), Toast.LENGTH_SHORT).show();
                                        MyApplication.limitSeconds = (Integer) SPUtil.get(getContext(), "limitSeconds", 0, "limitSeconds");
                                        firstConnect(position);
                                        try {
                                            if (!getActivity().isFinishing()) {
                                                BlEUtile.getmKProgressHUD(getActivity()).setLabel(getResources().getString(R.string.connecting)).dismiss();
                                            }
                                        } catch (Exception e1) {
                                            Log.e("e", "onSuccess: " + e1.toString());

                                        }
                                    }
                                });
                                map.clear();
                                map.put("address", device.getAddress());
                                okhttpUtils.postForm(Contants.BLUE_TIME, Contants.BASE_URL + "bluetime.link", map);
                            } else {
                                try {
                                    if (!getActivity().isFinishing()) {
                                        BlEUtile.getmKProgressHUD(getActivity()).setLabel(getResources().getString(R.string.connecting)).dismiss();
                                    }
                                } catch (Exception e) {
                                    Log.e("e", "onSuccess: " + e.toString());
                                }
                                Toast.makeText(getContext(), getResources().getString(R.string.unnet_message), Toast.LENGTH_SHORT).show();
                                MyApplication.limitSeconds = (Integer) SPUtil.get(getContext(), "limitSeconds", 0, "limitSeconds");
                            }
                        } else {
                            firstConnect(position);
                        }

                        //  rvDeviceAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onLongClick(int position) {
                    }
                });
            }
        }
    }

    private void firstConnect(int position) {
        final BluetoothDevice bluetoothDevice = (BluetoothDevice) devices.get(position);
        MyApplication.meBluetoothGattCallback = new MeBluetoothGattCallback();
        if (MyApplication.bluetoothGatt == null) {
            if (bluetoothDevice != null && bluetoothDevice.getName().startsWith("Metis Genie Mask")) {
//                if (BlEUtile.isNetworkConnected(getContext())) {
//                    connectBlueTooth(position, bluetoothDevice);
//                } else {
//                    Toast.makeText(getContext(), "没网了", Toast.LENGTH_SHORT).show();
//                }
                connectALYBlueTooth(position, bluetoothDevice);
            } else {
                Toast.makeText(getContext(), getResources().getString(R.string.fail_connect), Toast.LENGTH_SHORT).show();
            }
        } else if (MyApplication.bluetoothGatt != null && bluetoothDevice != null &&
                bluetoothDevice.equals(MyApplication.bluetoothGatt.getDevice())) {
            try {
                BlEUtile.getmKProgressHUD(getContext()).setLabel(getResources().getString(R.string.bluetooth_disconnecting)).show();
            } catch (Exception e) {

            }
            MyApplication.bluetoothGatt.disconnect();
//                                MyApplication.isConnected = false;

        } else if (MyApplication.bluetoothGatt != null && bluetoothDevice != null &&
                !bluetoothDevice.equals(MyApplication.bluetoothGatt.getDevice())) {
//                       BlEUtile.getmKProgressHUD(getContext()).setLabel("蓝牙断开中").show();
            MyApplication.bluetoothGatt.disconnect();
            MyApplication.meBluetoothGattCallback.setActivity(getActivity());
            MyApplication.meBluetoothGattCallback.setAdapter(rvDeviceAdapter);
            MyApplication.bluetoothGatt = bluetoothDevice.connectGatt(getContext(),
                    false, MyApplication.meBluetoothGattCallback);
//                                MyApplication.isConnected = false;

//        } else if (MyApplication.bluetoothGatt != null && MyApplication.isConnected && bluetoothDevice == null) {
//            Toast.makeText(getContext(), getResources().getString(R.string.bluetooth_disconnect), Toast.LENGTH_SHORT).show();
//            //非人为中断蓝牙连接
//            MyApplication.bluetoothGatt.disconnect();
       } else {
            MyApplication.bluetoothGatt.disconnect();
            Toast.makeText(getContext(), getResources().getString(R.string.bluetooth_disconnecting), Toast.LENGTH_SHORT).show();
        }
    }
/*
    去掉连接限制
 */
    private void connectALYBlueTooth(int position, BluetoothDevice bluetoothDevice) {

     //   if (MyApplication.limitCount < Contants.LIMIT_COUNT && MyApplication.limitSeconds < Contants.LIMIT_TIME * 60) {
        if (true) {
            MyApplication.meBluetoothGattCallback.setActivity(getActivity());
            MyApplication.meBluetoothGattCallback.setAdapter(rvDeviceAdapter);
            MyApplication.bluetoothGatt = bluetoothDevice.connectGatt(getContext(),
                    false, MyApplication.meBluetoothGattCallback);
            MyApplication.currentDevicePosition = position;
        } else {
            try {
                if (!getActivity().isFinishing()) {
                    BlEUtile.getmKProgressHUD(getActivity()).setLabel(getResources().getString(R.string.connecting)).dismiss();
                }
            } catch (Exception e) {
                Log.e("e", "onSuccess: " + e.toString());
            }
            builder.setTitle("")
                    .setMessage(R.string.bluetooth_limit_use)
                    .setPositiveButton(R.string.ok, null)
                    .show();
        }
    }

    private void connectBlueTooth(final int position, final BluetoothDevice bluetoothDevice) {
        bmobUtil = new BmobUtil(new BmobListener() {
            @Override
            public void onSuccess(int code, List<Numb> list) {
                if (code == 0) {
                    if (list.size() == 0) {
                        MyApplication.limitCount = 0;
                    } else {
                        MyApplication.limitCount = list.get(0).getNumberlong();
                    }
                    if (MyApplication.limitCount < Contants.LIMIT_COUNT && MyApplication.limitSeconds < Contants.LIMIT_TIME * 60) {
                        MyApplication.meBluetoothGattCallback.setActivity(getActivity());
                        MyApplication.meBluetoothGattCallback.setAdapter(rvDeviceAdapter);
                        MyApplication.bluetoothGatt = bluetoothDevice.connectGatt(getContext(),
                                false, MyApplication.meBluetoothGattCallback);
                        MyApplication.currentDevicePosition = position;
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Log.e("test", "onServicesDiscovered: 我想问一下 ");
                                //    MyApplication.meBluetoothGattCallback.testSpecial();
                                Log.e("test", "onServicesDiscovered: 你去哪里了 ");
                            }
                        }, 3000);


                        Log.e("text", "onClick: " + 111);
                    } else {
                        try {
                            if (!getActivity().isFinishing()) {
                                BlEUtile.getmKProgressHUD(getActivity()).setLabel(getResources().getString(R.string.connecting)).dismiss();
                            }
                        } catch (Exception e) {
                            Log.e("e", "onSuccess: " + e.toString());
                        }
                        builder.setTitle("")
                                .setMessage(R.string.bluetooth_limit_use)
                                .setPositiveButton(R.string.ok, null)
                                .show();
                    }
                }
            }

            @Override
            public void onError(int code, BmobException e) {
                Log.e("===", e + "========");
                builder.setTitle(R.string.limit_net_fail_title)
                        .setMessage(R.string.limit_net_fail_message)
                        .setNegativeButton(R.string.cancle, null)
                        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                bmobUtil.getBLEDataFromBmob(bluetoothDevice.getAddress(), 0);
                            }
                        }).show();
            }
        });
        bmobUtil.getBLEDataFromBmob(bluetoothDevice.getAddress(), 0);
    }

    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        /**
         * @param device
         * @param rssi----------------
         * @param scanRecord
         */
        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            showDevice(device);
            rvDeviceAdapter.notifyDataSetChanged();
        }
    };

}
